package com.example.cdpbookstore.dao.impl;

import com.example.cdpbookstore.dao.CustomerDao;
import com.example.cdpbookstore.pojo.entity.Customer;
import com.example.cdpbookstore.tool.C3P0Tool;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class CustomerDaoImpl implements CustomerDao {
    @Override
    public boolean save(Customer customer) {
        String sql = "insert into tb_customer (id, username, password, email, avatar, name, mobile, address, creationTime, updateTime)" +
                "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try {
            int update = C3P0Tool.queryRunner.update(sql,
                    customer.getId(),
                    customer.getUsername(),
                    customer.getPassword(),
                    customer.getEmail(),
                    customer.getAvatar(),
                    customer.getName(),
                    customer.getMobile(),
                    customer.getAddress(),
                    customer.getCreationTime(),
                    customer.getUpdateTime()
            );
            return update > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Customer getByUsernameOrEmail(String account) {
        String sql = "select * from tb_customer where username=? or email=?";

        try {
            return C3P0Tool.queryRunner.query(sql, new BeanHandler<>(Customer.class), account, account);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Customer getById(String id) {
        String sql = "select * from tb_customer where id=?";

        try {
            return C3P0Tool.queryRunner.query(sql, new BeanHandler<>(Customer.class), id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean update(Customer customer) {
        String sql = "update tb_customer set `username`=?, `password`=?, `email`=?, `avatar`=?, " +
                "`name`=?, `mobile`=?, `address`=?, `state`=?, `creationTime`=?, `updateTime`=? where `id`=?";

        try {
            int update = C3P0Tool.queryRunner.update(sql,
                    customer.getUsername(),
                    customer.getPassword(),
                    customer.getEmail(),
                    customer.getAvatar(),
                    customer.getName(),
                    customer.getMobile(),
                    customer.getAddress(),
                    customer.getState(),
                    customer.getCreationTime(),
                    customer.getUpdateTime(),
                    customer.getId());
            return update > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
